import { removeToken, setToken, getToken } from "@/utils/auth";
import { loginApi, getInfo } from "@/api/user";
const state = {
  token: getToken(), //从缓存中读取token
  userInfo: {}, //存储用户基本资料
};

const mutations = {
  setToken(state, token) {
    state.token = token;
    //同步到缓存
    setToken(token);
  },
  //删除token
  removeToken(state) {
    state.token = null;
    removeToken();
  },
  //获取用户数据
  getuserInfo(state, userInfo) {
    state.userInfo = userInfo;
  },
};

const actions = {
  async login(context, data) {
    //调用登录接口
    const token = await loginApi(data);
    //返回token
    context.commit("setToken", token);
  },
  //调用获取用户信息接口
  async getuserInfo(context) {
    const result = await getInfo();
    context.commit("getuserInfo", result);
  },
  //退出登录
  logout(context) {
    //删除token
    context.commit("removeToken");
    //将用户信息初始化
    context.commit("getuserInfo", {});
  },
};

export default {
  namespaced: true, //开启命名空间
  state,
  mutations,
  actions,
};
